/*
 * morse.h - Copyright (C) 2011 Beastieux Zeroo <the.beastieux@gmail.com>
 *

 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301, USA.
 */

#include <stdio.h> 
#include <string.h> 
#include <ctype.h> 

void encode(const char *s, char *resolv);
void decode(const char *morse, char *resolv);

static const struct
{
   const char letter, *morse;
} Code[] =
{
   { 'A', ".- "   },{ 'B', "-... " },{ 'C', "-.-. " },{ 'D', "-.. "  },
   { 'E', ". "    },{ 'F', "..-. " },{ 'G', "--. "  },{ 'H', ".... " },
   { 'I', ".. "   },{ 'J', ".--- " },{ 'K', ".-.- " },{ 'L', ".-.. " },
   { 'M', "-- "   },{ 'N', "-. "   },{ 'O', "--- "  },{ 'P', ".--. " },
   { 'Q', "--.- " },{ 'R', ".-. "  },{ 'S', "... "  },{ 'T', "- "    },
   { 'U', "..- "  },{ 'V', "...- " },{ 'W', ".-- "  },{ 'X', "-..- " },
   { 'Y', "-.-- " },{ 'Z', "--.. " },{ ' ', "  "    },
   { '1', ".---- "  },{ '2', "..--- " },{ '3', "...-- "  },{ '4', "....- " },
   { '5', "..... "  },{ '6', "-.... " },{ '7', "--... "  },{ '8', "---.. " },
   { '9', "----. "  },{ '0', "----- " },{ ',', "--..-- "  },{ '.', ".-.-.- "  },
   { '?', "..--.. "  },{ '!', "..--. " },{ ':', "---... "  },{ '"', ".----. "  },
   { '/', "-..-. "  },{ '(', "-.--. " },{ ')', "-.--.- "  },{ '&', ".-... "  },
   { ';', "-.-.-. "  },{ '=', "-...- " },{ '+', ".-.-. "  },{ '-', "-....- "  },
   { '_', "..--.- "  },{ '$', "...-..- " },{ '@', ".--.-. "  },
};

void encode(const char *s, char *resolv)
{
   size_t i, j;
   for ( i = 0; s[i]; ++i )
   {
      for ( j = 0; j < sizeof Code / sizeof *Code; ++j )
      {
         if ( toupper(s[i]) == Code[j].letter )
         {
	    strcat(resolv,Code[j].morse);
	    break;
         }
      }
   }

}

void decode(const char *morse, char *resolv)
{
   size_t i, j, k;
   i=0,k=-1;

   for ( i = 0; morse[i];k++ )
   {
      if( k == strlen(morse) || k == 0 )
      {
	   break;
      }

      for ( j = 0; j < sizeof Code / sizeof *Code; ++j )
      {
         	size_t size = strlen(Code[j].morse);
	 

		if ( memcmp(Code[j].morse, &morse[i], size) == 0 )
		{

		    strcat(resolv,&Code[j].letter);
		    
		    i += size;
		    k=i;
		    break;
		}	 
      }

      
	
    }

}
